<template>
  <div class="forgot-password-container">
    <div class="forgot-password-box">
      <div class="logo-section">
        <div class="logo-icon">
          <i class="icon-graduation-cap"></i>
        </div>
        <h2>农民技能提升就业培训大数据平台</h2>
        <p>找回密码</p>
      </div>
      
      <div v-if="!emailSent" class="forgot-form">
        <div class="instruction">
          <i class="icon-info"></i>
          <p>请输入您注册时使用的邮箱地址，我们将向您发送密码重置链接。</p>
        </div>
        
        <form @submit.prevent="handleForgotPassword">
          <!-- 错误提示 -->
          <div v-if="errorMessage" class="error-message">
            <i class="icon-alert-circle"></i>
            {{ errorMessage }}
          </div>
          
          <div class="form-group">
            <label>
              <i class="icon-mail"></i>
              邮箱地址
            </label>
            <input
              v-model="email"
              type="email"
              required
              placeholder="请输入注册邮箱"
              :disabled="loading"
              @blur="validateEmail"
            />
            <span v-if="emailError" class="field-error">{{ emailError }}</span>
          </div>
          
          <button type="submit" class="send-btn" :disabled="loading || !isEmailValid">
            <i v-if="loading" class="icon-loading"></i>
            {{ loading ? '发送中...' : '发送重置链接' }}
          </button>
        </form>
      </div>
      
      <div v-else class="success-section">
        <div class="success-icon">
          <i class="icon-mail-check"></i>
        </div>
        <h3>邮件已发送</h3>
        <p>我们已向 <strong>{{ email }}</strong> 发送了密码重置链接。</p>
        <p>请检查您的邮箱（包括垃圾邮件文件夹），并点击链接重置密码。</p>
        
        <div class="resend-section">
          <p>没有收到邮件？</p>
          <button 
            @click="resendEmail" 
            class="resend-btn"
            :disabled="resendCooldown > 0"
          >
            {{ resendCooldown > 0 ? `${resendCooldown}秒后可重发` : '重新发送' }}
          </button>
        </div>
      </div>
      
      <div class="back-to-login">
        <router-link to="/login">
          <i class="icon-arrow-left"></i>
          返回登录
        </router-link>
      </div>
      
      <div class="forgot-footer">
        <p>© 2024 农民技能提升就业培训大数据平台</p>
      </div>
    </div>
    
    <!-- 背景装饰 -->
    <div class="background-decoration">
      <div class="decoration-1"></div>
      <div class="decoration-2"></div>
      <div class="decoration-3"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onUnmounted } from 'vue'

const loading = ref(false)
const emailSent = ref(false)
const email = ref('')
const errorMessage = ref('')
const emailError = ref('')
const resendCooldown = ref(0)

let resendTimer = null

// API 基础配置
const API_BASE_URL = process.env.VUE_APP_API_BASE_URL || 'http://localhost:8000'

// 忘记密码API调用
const forgotPasswordAPI = async (email) => {
  const response = await fetch(`${API_BASE_URL}/auth/forgot-password`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ email })
  })
  
  if (!response.ok) {
    const errorData = await response.json()
    throw new Error(errorData.detail || '发送失败')
  }
  
  return await response.json()
}

// 验证邮箱
const validateEmail = () => {
  const emailValue = email.value.trim()
  if (!emailValue) {
    emailError.value = '邮箱不能为空'
    return false
  }
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(emailValue)) {
    emailError.value = '请输入有效的邮箱地址'
    return false
  }
  emailError.value = ''
  return true
}

const isEmailValid = computed(() => {
  return email.value && !emailError.value
})

// 处理忘记密码
const handleForgotPassword = async () => {
  if (!validateEmail()) {
    errorMessage.value = '请输入有效的邮箱地址'
    return
  }
  
  loading.value = true
  errorMessage.value = ''
  
  try {
    await forgotPasswordAPI(email.value)
    emailSent.value = true
    startResendCooldown()
  } catch (error) {
    console.error('发送重置链接失败:', error)
    errorMessage.value = error.message || '发送失败，请稍后重试'
  } finally {
    loading.value = false
  }
}

// 重新发送邮件
const resendEmail = async () => {
  if (resendCooldown.value > 0) return
  
  loading.value = true
  try {
    await forgotPasswordAPI(email.value)
    startResendCooldown()
  } catch (error) {
    console.error('重新发送失败:', error)
    errorMessage.value = error.message || '重新发送失败，请稍后重试'
  } finally {
    loading.value = false
  }
}

// 开始重发倒计时
const startResendCooldown = () => {
  resendCooldown.value = 60
  resendTimer = setInterval(() => {
    resendCooldown.value--
    if (resendCooldown.value <= 0) {
      clearInterval(resendTimer)
      resendTimer = null
    }
  }, 1000)
}

// 清理定时器
onUnmounted(() => {
  if (resendTimer) {
    clearInterval(resendTimer)
  }
})
</script>

<style scoped>
.forgot-password-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  position: relative;
  overflow: hidden;
}

.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
}

.decoration-1,
.decoration-2,
.decoration-3 {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
}

.decoration-1 {
  width: 200px;
  height: 200px;
  top: 10%;
  right: 10%;
  animation: float 6s ease-in-out infinite;
}

.decoration-2 {
  width: 150px;
  height: 150px;
  bottom: 20%;
  left: 15%;
  animation: float 8s ease-in-out infinite reverse;
}

.decoration-3 {
  width: 100px;
  height: 100px;
  top: 60%;
  right: 20%;
  animation: float 10s ease-in-out infinite;
}

@keyframes float {
  0%, 100% { transform: translateY(0px); }
  50% { transform: translateY(-20px); }
}

.forgot-password-box {
  background: white;
  padding: 40px;
  border-radius: 16px;
  box-shadow: 0 20px 40px rgba(0,0,0,0.1);
  width: 100%;
  max-width: 420px;
  position: relative;
}

.logo-section {
  text-align: center;
  margin-bottom: 32px;
}

.logo-icon {
  width: 80px;
  height: 80px;
  background: linear-gradient(135deg, #4F46E5, #7C3AED);
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 20px;
  box-shadow: 0 8px 20px rgba(79, 70, 229, 0.3);
}

.logo-icon i {
  font-size: 36px;
  color: white;
}

.logo-section h2 {
  margin: 0 0 8px 0;
  color: #1F2937;
  font-size: 20px;
  font-weight: 600;
}

.logo-section p {
  margin: 0;
  color: #6B7280;
  font-size: 14px;
}

.instruction {
  background: #F0F9FF;
  border: 1px solid #BAE6FD;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 24px;
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.instruction i {
  color: #0EA5E9;
  margin-top: 2px;
  flex-shrink: 0;
}

.instruction p {
  margin: 0;
  color: #0F172A;
  font-size: 14px;
  line-height: 1.5;
}

.forgot-form {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.error-message {
  background: #FEF2F2;
  border: 1px solid #FECACA;
  color: #DC2626;
  padding: 12px 16px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  color: #374151;
  font-size: 14px;
}

.form-group label i {
  color: #6B7280;
}

.form-group input {
  padding: 14px 16px;
  border: 2px solid #E5E7EB;
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.2s;
}

.form-group input:focus {
  outline: none;
  border-color: #4F46E5;
  box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
}

.form-group input:disabled {
  background-color: #F9FAFB;
  cursor: not-allowed;
}

.field-error {
  color: #DC2626;
  font-size: 12px;
}

.send-btn {
  padding: 14px;
  background: linear-gradient(135deg, #4F46E5, #7C3AED);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  box-shadow: 0 4px 12px rgba(79, 70, 229, 0.3);
}

.send-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 6px 16px rgba(79, 70, 229, 0.4);
}

.send-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
}

.success-section {
  text-align: center;
}

.success-icon {
  width: 80px;
  height: 80px;
  background: linear-gradient(135deg, #10B981, #059669);
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 24px;
  box-shadow: 0 8px 20px rgba(16, 185, 129, 0.3);
}

.success-icon i {
  font-size: 36px;
  color: white;
}

.success-section h3 {
  margin: 0 0 16px 0;
  color: #1F2937;
  font-size: 24px;
  font-weight: 600;
}

.success-section p {
  margin: 0 0 12px 0;
  color: #6B7280;
  font-size: 14px;
  line-height: 1.5;
}

.success-section strong {
  color: #4F46E5;
  font-weight: 600;
}

.resend-section {
  margin-top: 32px;
  padding-top: 24px;
  border-top: 1px solid #E5E7EB;
}

.resend-section p {
  margin: 0 0 12px 0;
  color: #6B7280;
  font-size: 14px;
}

.resend-btn {
  background: transparent;
  color: #4F46E5;
  border: 2px solid #4F46E5;
  padding: 10px 20px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.resend-btn:hover:not(:disabled) {
  background: #4F46E5;
  color: white;
}

.resend-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.back-to-login {
  margin-top: 32px;
  text-align: center;
  padding-top: 24px;
  border-top: 1px solid #E5E7EB;
}

.back-to-login a {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  color: #6B7280;
  text-decoration: none;
  font-size: 14px;
  transition: color 0.2s;
}

.back-to-login a:hover {
  color: #4F46E5;
}

.forgot-footer {
  margin-top: 20px;
  text-align: center;
}

.forgot-footer p {
  margin: 0;
  color: #6B7280;
  font-size: 12px;
}

.icon-loading {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 响应式设计 */
@media (max-width: 480px) {
  .forgot-password-container {
    padding: 16px;
  }
  
  .forgot-password-box {
    padding: 32px 24px;
  }
  
  .logo-section h2 {
    font-size: 18px;
  }
}
</style>